#include "sample.h"
#include "data_processor.h"
#define LOG_SET_LOCAL_LEVEL LOG_LEVEL_NONE
#include "log.h"

static sample_t *samCache;

__weak void Sample_Complete(sample_t *thiz) {
    LOG_debug("Sample complete once!!!");
    DPR_waitQ_post(thiz->In->HeadPtr, 50);
}

static void _sample_task(const void *args) 
{
    while(true) 
    {
        if (Buffer_IsFull(samCache->In)) {
            Sample_Complete(samCache);
            Buffer_Reset(samCache->In);
        }
        uint32_t data = HAL_AD7190_Step(samCache->Ad7190_Handle, 10);
//        uint32_t data = 0x12345678;
        Buffer_Put(samCache->In, data >> 24);
        Buffer_Put(samCache->In, data >> 16);
        Buffer_Put(samCache->In, data >> 8);
        Buffer_Put(samCache->In, data >> 0);
        osDelay(20U);
    }
}

HAL_StatusTypeDef Sample_Start(sample_t *thiz) {

    assert_param(thiz != NULL);
    assert_param(thiz->In != NULL);
    assert_param(thiz->Ad7190_Handle != NULL);
    assert_param(thiz->Ad7190_Handle->State == HAL_AD7190_STATE_READY);

    samCache = thiz;
    LOG_info("Sample start!!!");
    
    osThreadDef(sampleThread, _sample_task, osPriorityHigh, NULL, 128U);
    osThreadCreate(osThread(sampleThread), NULL);
    
    return HAL_OK;
}

HAL_StatusTypeDef Sample_Stop(sample_t *thiz)
{

    assert_param(thiz != NULL);
    assert_param(thiz->In != NULL);

    LOG_info("Sample stop!!!");
    return HAL_OK;
}

uint32_t Sample_Step(sample_t *thiz) {

    assert_param(thiz != NULL);
    assert_param(thiz->Ad7190_Handle->State == HAL_AD7190_STATE_READY);

    return HAL_AD7190_Step(thiz->Ad7190_Handle, 10);
}
